<?php
/**
 * @package panel
 * @subpackage panel.environment.db
 */
/**
 * Overload of PDO statement:
 * Use auth check
 * Use logging using panel.logger.query
 * @author Dmitry Bakaleinik (code)
 */
class panel__db__pdo_statement
	extends PDOStatement {

	/**
	 * Build query using PDOStatement query string
	 * @param  array $_ arguments to be passed into query
	 * @return unknown_type
	 */
	public function buildQuery( array $_ ) {

		$query = $this->queryString;

		foreach( $_ as $_k => $_v ) {

			switch(TRUE) {

			case is_int($_k):
				$query = str_replace_limit("?", "'" . mysql_escape_string($_v) . "'", $query, 1);
				break;

			case is_string($_k):
				$query = str_replace_limit($_k, "'" . mysql_escape_string($_v) . "'", $query, 1);
				break;

			}	# switch

		}	# foreach

		return $query . ";";

	}	# Function

	/**
	 * Execute query
	 * @param string|array $_ query
	 * @param array $_options_
	 * @return array
	**/
	public function execute( $_ = array(), array $_options_ = array() ) {

		/**
		 * Force drop cache
		 */
		switch( TRUE ) {

		case (stripos($this->queryString, "insert") !== FALSE):
		case (stripos($this->queryString, "delete") !== FALSE):
		case (stripos($this->queryString, "update") !== FALSE):
		case (stripos($this->queryString, "replace") !== FALSE):

			$time = microtime(TRUE);

			$R = parent::execute($_);

			/**
			 * Force drop cache
			 */
			p()->cache()->drop();

			$statement = array(
				"time"	         => date("Y-m-d H:i:s"),
				"mtime"          => microtime(TRUE) - $time,
				"host"           => p()->db()->getConnection()->getHost(),
				"last_insert_id" => p()->db()->getConnection()->lastInsertId(),
				"affected_rows"  => $this->rowCount(),
				"queries"        => array( array(
					"return"         => $this,
					"last_insert_id" => p()->db()->getConnection()->lastInsertId(),
					"sql"            => $this->buildQuery($_),
					"affected_rows"  => $this->rowCount(),
				) )
			);

			if( panel__settings__environment::isLogQuerires() ) {
				panel__logger__query::getInstance()->logStatement($statement); }

			break;

		default:

			$R = parent::execute($_);

			break;

		}	# switch

		return $R;

	}	# Function

}	# Function

/* EOF */